package nl.grol.yakshop.web.servlet;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.grol.yakshop.binding.MyYakShopModule;
import nl.grol.yakshop.domain.model.Stock;
import nl.grol.yakshop.domain.service.StockCalculator;
import nl.grol.yakshop.domain.service.StockCalculatorI;
import nl.grol.yakshop.util.InvalidInputException;
import nl.grol.yakshop.web.servlet.json.JsonConverter;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;

@Singleton
@SuppressWarnings("serial")
public class StockServlet extends BaseJsonServlet {
    private static final Logger LOGGER = Logger.getLogger(StockServlet.class.getName());

    @Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

    	int httpResponseStatus = 500;
    	
    	try {
			
    		/*
    		 * Validate request
    		 */
			Integer dayOffsetSinceShopOpening = extractLastPathSegmentFromRequest(req);

			/*
			 * Get required services from guice
			 */
			Injector injector = Guice.createInjector(new MyYakShopModule());
			StockCalculatorI stockCalculator = injector.getInstance(StockCalculator.class);
			
			/*
			 * Call business logic
			 */
			Stock stock = stockCalculator.determineStockOnDay(dayOffsetSinceShopOpening);
			
			/*
			 * Convert to json
			 */
			String stockAsJson = JsonConverter.makeJsonStock( 
					stock.getMilk(), stock.getSkins() );
	
			/*
			 * Write response body
			 */
			writeSuccessResponse( req, resp, 200, stockAsJson);
			
		} catch( InvalidInputException exc ) {
			
			LOGGER.warning("Error parsing day from request " + exc.getMessage() );
			httpResponseStatus = 400;
			writeErrorResponse( req, resp, httpResponseStatus, exc);

		} catch( Exception exc ) {
			
			LOGGER.warning("Undefined error " + exc.getMessage() );
			/*
			 * Report error
			 */
			writeErrorResponse( req, resp, httpResponseStatus, exc);
	
		}
	
	}
}
